﻿
namespace ManageData
{
    internal class 为主实体单独添加从实体
    {
        void MyMethod()
        {
            // 查询跟踪实体后添加
            using (var db = new BasicDbContext())
            {
                var mainEntity = db.MainEntities.First();

                var sub1 = new SubEntity { Time = DateTimeOffset.Now };
                var sub2 = new SubEntity { Time = DateTimeOffset.Now.AddDays(1) };
                var sub3 = new SubEntity { Time = DateTimeOffset.Now.AddDays(2) };

                mainEntity.SubEntities.Add(sub1);
                sub2.MainEntity = mainEntity;
                sub3.MainEntityId = mainEntity.Id;

                db.SubEntities.AddRange(sub2, sub3);
                db.SaveChanges();
            }

            // 直接添加
            using (var db = new BasicDbContext())
            {
                var mainEntity = new MainEntity { Id = 1 };

                var sub1 = new SubEntity { Time = DateTimeOffset.Now };
                var sub2 = new SubEntity { Time = DateTimeOffset.Now.AddDays(1) };

                mainEntity.SubEntities.Add(sub1);
                sub2.MainEntity = mainEntity;
                db.MainEntities.Update(mainEntity);
                db.SubEntities.Add(sub2);

                var sub3 = new SubEntity { Time = DateTimeOffset.Now.AddDays(2) };
                sub3.MainEntityId = 2;

                db.SubEntities.Add(sub3);
            }
        }
    }
}
